<template>
  <view class="qr-code-container">
    <view class="qr-header">
      <text class="qr-title">订单二维码</text>
      <text class="qr-subtitle">请向工作人员出示此二维码</text>
    </view>
    
    <view class="qr-content">
      <view v-if="loading" class="qr-loading">
        <uni-load-more status="loading" :content-text="loadingText"></uni-load-more>
      </view>
      
      <view v-else-if="error" class="qr-error">
        <uni-icons type="info" size="48" color="#ff5722"></uni-icons>
        <text class="error-text">{{ error }}</text>
        <button class="retry-btn" @click="generateQRCode">重新生成</button>
      </view>
      
      <view v-else class="qr-display">
        <view class="qr-image-container" @click="previewQRCode">
          <image 
            :src="qrImageUrl" 
            class="qr-image"
            mode="aspectFit"
            @error="onImageError"
            @load="onImageLoad"
          />
          <view v-if="!imageLoaded" class="image-placeholder">
            <uni-icons type="image" size="48" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <view class="qr-info">
          <view class="info-item">
            <text class="info-label">订单号：</text>
            <text class="info-value">{{ orderData.orderNumber }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">金额：</text>
            <text class="info-value">¥{{ orderData.finalAmount }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">状态：</text>
            <text class="info-value status" :class="statusClass">{{ statusText }}</text>
          </view>
        </view>
        
        <view class="qr-actions">
          <button class="action-btn refresh-btn" @click="refreshQRCode">
            <uni-icons type="refresh" size="16"></uni-icons>
            <text>刷新</text>
          </button>
          <button class="action-btn save-btn" @click="saveToAlbum">
            <uni-icons type="download" size="16"></uni-icons>
            <text>保存</text>
          </button>
        </view>
        
        <view class="qr-tips">
          <text class="tips-text">• 二维码24小时内有效</text>
          <text class="tips-text">• 请在门店出示给工作人员扫描</text>
          <text class="tips-text">• 如无法扫描，请点击刷新重新生成</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { orderApi } from '@/api/orders'

export default {
  name: 'OrderQRCode',
  props: {
    orderId: {
      type: [String, Number],
      required: true
    },
    orderData: {
      type: Object,
      default: () => ({})
    },
    size: {
      type: Number,
      default: 256
    }
  },
  data() {
    return {
      loading: false,
      error: '',
      qrImageUrl: '',
      qrToken: '',
      qrUrl: '',
      imageLoaded: false,
      loadingText: {
        contentdown: '生成中...',
        contentrefresh: '生成中...',
        contentnomore: '生成完成'
      }
    }
  },
  computed: {
    statusText() {
      const statusMap = {
        'pending': '待确认',
        'confirmed': '已确认',
        'processing': '处理中',
        'printing': '打印中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[this.orderData.status] || '未知状态'
    },
    statusClass() {
      const classMap = {
        'pending': 'status-pending',
        'confirmed': 'status-confirmed',
        'processing': 'status-processing',
        'printing': 'status-printing',
        'completed': 'status-completed',
        'cancelled': 'status-cancelled'
      }
      return classMap[this.orderData.status] || ''
    }
  },
  mounted() {
    this.generateQRCode()
  },
  methods: {
    async generateQRCode() {
      if (!this.orderId) {
        this.error = '订单ID不能为空'
        return
      }
      
      this.loading = true
      this.error = ''
      this.imageLoaded = false
      
      try {
        const response = await orderApi.getOrderQRCode(this.orderId, {
          size: this.size,
          format: 'base64'
        })
        
        if (response.success) {
          this.qrImageUrl = `data:image/png;base64,${response.data.image}`
          this.qrToken = response.data.token
          this.qrUrl = response.data.url
          
          this.$emit('qr-generated', {
            token: this.qrToken,
            url: this.qrUrl,
            image: response.data.image
          })
        } else {
          this.error = response.message || '生成二维码失败'
        }
      } catch (error) {
        console.error('生成二维码失败:', error)
        this.error = error.message || '网络错误，请重试'
      } finally {
        this.loading = false
      }
    },
    
    async refreshQRCode() {
      this.loading = true
      this.error = ''
      
      try {
        const response = await orderApi.refreshOrderQRCode(this.orderId)
        
        if (response.success) {
          // 重新生成二维码图片
          await this.generateQRCode()
          
          uni.showToast({
            title: '二维码已刷新',
            icon: 'success'
          })
          
          this.$emit('qr-refreshed', {
            token: response.data.token,
            url: response.data.url
          })
        } else {
          this.error = response.message || '刷新二维码失败'
        }
      } catch (error) {
        console.error('刷新二维码失败:', error)
        this.error = error.message || '网络错误，请重试'
      } finally {
        this.loading = false
      }
    },
    
    previewQRCode() {
      if (!this.qrImageUrl) return
      
      uni.previewImage({
        urls: [this.qrImageUrl],
        current: 0
      })
    },
    
    async saveToAlbum() {
      if (!this.qrImageUrl) {
        uni.showToast({
          title: '二维码未生成',
          icon: 'none'
        })
        return
      }
      
      try {
        // 先下载图片到本地
        const downloadResult = await uni.downloadFile({
          url: this.qrImageUrl
        })
        
        if (downloadResult.statusCode === 200) {
          // 保存到相册
          await uni.saveImageToPhotosAlbum({
            filePath: downloadResult.tempFilePath
          })
          
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          this.$emit('qr-saved')
        } else {
          throw new Error('下载图片失败')
        }
      } catch (error) {
        console.error('保存二维码失败:', error)
        
        if (error.errMsg && error.errMsg.includes('auth')) {
          uni.showModal({
            title: '提示',
            content: '需要授权访问相册才能保存图片',
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                uni.openSetting()
              }
            }
          })
        } else {
          uni.showToast({
            title: '保存失败',
            icon: 'none'
          })
        }
      }
    },
    
    onImageLoad() {
      this.imageLoaded = true
    },
    
    onImageError() {
      this.error = '二维码图片加载失败'
      this.imageLoaded = false
    }
  }
}
</script>

<style lang="scss" scoped>
.qr-code-container {
  padding: 20rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.qr-header {
  text-align: center;
  margin-bottom: 30rpx;
  
  .qr-title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .qr-subtitle {
    display: block;
    font-size: 28rpx;
    color: #666;
  }
}

.qr-content {
  min-height: 400rpx;
}

.qr-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
}

.qr-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  
  .error-text {
    margin: 20rpx 0;
    font-size: 28rpx;
    color: #ff5722;
    text-align: center;
  }
  
  .retry-btn {
    background: #007aff;
    color: #fff;
    border: none;
    border-radius: 8rpx;
    padding: 16rpx 32rpx;
    font-size: 28rpx;
  }
}

.qr-display {
  .qr-image-container {
    position: relative;
    width: 400rpx;
    height: 400rpx;
    margin: 0 auto 30rpx;
    border: 2rpx solid #eee;
    border-radius: 12rpx;
    overflow: hidden;
    
    .qr-image {
      width: 100%;
      height: 100%;
    }
    
    .image-placeholder {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f5f5;
    }
  }
  
  .qr-info {
    margin-bottom: 30rpx;
    
    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
      
      .info-label {
        font-size: 28rpx;
        color: #666;
        width: 120rpx;
      }
      
      .info-value {
        font-size: 28rpx;
        color: #333;
        flex: 1;
        
        &.status {
          font-weight: bold;
          
          &.status-pending { color: #ff9800; }
          &.status-confirmed { color: #2196f3; }
          &.status-processing { color: #9c27b0; }
          &.status-printing { color: #ff5722; }
          &.status-completed { color: #4caf50; }
          &.status-cancelled { color: #f44336; }
        }
      }
    }
  }
  
  .qr-actions {
    display: flex;
    gap: 20rpx;
    margin-bottom: 30rpx;
    
    .action-btn {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8rpx;
      padding: 20rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
      border: none;
      
      &.refresh-btn {
        background: #f0f0f0;
        color: #333;
      }
      
      &.save-btn {
        background: #007aff;
        color: #fff;
      }
    }
  }
  
  .qr-tips {
    .tips-text {
      display: block;
      font-size: 24rpx;
      color: #999;
      line-height: 1.5;
      margin-bottom: 8rpx;
    }
  }
}
</style>